import { onBeforeUnmount, onMounted, ref } from 'vue'
import _ from 'lodash'
const navBarHanlder = () => {
  const scrollTop = ref(0)
  const color = ref('')
  //滚动改变元素背景方法
  function handleScroll() {
    scrollTop.value = document.documentElement.scrollTop
    if (scrollTop.value > 0) {
      color.value = '#ffffff'
      // console.log(color.value)
    }
    //滚轮往下滑动之后再滑回顶部，背景恢复白色
    if (scrollTop.value < 2) color.value = ''
  }
  //节流函数:单位时间内只执行一次
  const lodashHandle = _.throttle(() => {
    handleScroll()
  }, 300)
  //监听页面滚动事件
  onMounted(() => {
    window.addEventListener('scroll', lodashHandle)
  })
  // 离开当前组件别忘记移除事件监听
  onBeforeUnmount(() => {
    window.removeEventListener('scroll', lodashHandle)
  })
}
export default navBarHanlder
